#define _CRT_SECURE_NO_WARNINGS 1
#include"string.h"
namespace xs {
	void string::reserve(int n) {
		if (n > _capacity) {
			char* tmp = new char[n+1];
			strcpy(tmp, _str);
			delete[] _str;
			_str = tmp;
			_capacity = n;
		}
	}
	void string::push_back(char ch) {
		if (_size == _capacity) {
			reserve(_capacity == 0 ? 4 : _capacity * 2);
		}
		_str[_size] = ch;
		_size++;
		_str[_size] = '\0';
	};
	const string& string::operator+=(char ch) {
		push_back(ch);
		return *this;
	}
	void string::append(const char* str) {
		int len = strlen(str);
		if (len + _size > _capacity) {
			reserve(len + _size > 2 * _capacity ? len + _size : 2 * _capacity);
		}
		strcpy(_str + len, str);
		_size += len;
	}
	const string& string::operator+=(const char* str) {
		append(str);
		return *this;
	};
	void string::insert(size_t pos, char ch) {
		assert(pos <= _size);
		if (_size == _capacity) {
			reserve(_capacity == 0 ? 4 : _capacity * 2);
		}
		size_t end = _size+1;
		while (end > pos) {
			_str[end] = _str[end-1];
			--end;
		}
		_str[pos] = ch;
		_size++; 
	}
	void string::insert(size_t pos, const char* str) {
		assert(pos <= _size);
		size_t len = strlen(str);
		if (len == 0) {
			return;
		}
		if (_size + len > _capacity) {
			reserve(len + _size > 2 * _capacity ? len + _size : 2 * _capacity);
		}
		size_t end = _size + len;
		while (end > pos+len-1) {
			_str[end] = _str[end - len];
			--end;
		}
		for (size_t i = 0; i < len; i++) {
			_str[pos + i] = str[i];
		}
	}

	void string::erase(size_t pos, size_t len) {
		if (len > _size - pos) {
			_str[pos] = '\0';
			_size = pos;
		}
		else {
			for (size_t i = pos + len; i <= _size; i++) {
				_str[i - len] = _str[i];
			}
			_size -= len;
		}
	};

	/*size_t string::find(const char* ch, size_t pos = 0) {
		assert(pos < _size);
		const char* ptr = strstr(_str + pos, _str);
		if (ptr == nullptr) {
			return npos;
		}
		else {
			return ptr - _str;
		}
	}*/
}